package com.softa.common.sysconfig.shiro.encrypt;

import com.softa.common.entity.SysUser;
import com.softa.common.sysconfig.properties.PandaCoreProperties;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author hasee
 */
@Service
public class PasswordHelper {

    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    @Autowired
    private PandaCoreProperties pandaCoreProperties;

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void encryptPassword(SysUser user) {

        String salt = randomNumberGenerator.nextBytes().toHex();
        user.setSalt(salt);

        String newPassword = new SimpleHash(
                pandaCoreProperties.getShiro().getAlgorithmName(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getUsername()+salt),
                pandaCoreProperties.getShiro().getHashIterations()).toHex();

        user.setPassword(newPassword);
    }

    public void encryptPassword(SysUser user, String salt) {

        user.setSalt(salt);

        String newPassword = new SimpleHash(
                pandaCoreProperties.getShiro().getAlgorithmName(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getUsername()+salt),
                pandaCoreProperties.getShiro().getHashIterations()).toHex();

        user.setPassword(newPassword);
    }
}
